package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.common.Constants;
import com.cjack.frenchexcel.config.ErrorCodeDefine;
import com.cjack.frenchexcel.dao.UserDao;
import com.cjack.frenchexcel.enumInfo.InvoiceReviewStatusEnum;
import com.cjack.frenchexcel.model.AdminUserModel;
import com.cjack.frenchexcel.table.AdminUserTable;
import com.cjack.frenchexcel.util.AssertUtil;
import com.cjack.frenchexcel.util.DateFormatUtil;
import com.cjack.frenchexcel.util.ModelUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 登录相关的用户操作service
 * Created by root on 10/5/19
 */
@Service
public class UserService {

    @Autowired
    private UserDao dao;
    @Autowired
    private UserAdminService userAdminService;

    public AdminUserModel login(String jobNumber, String password) {
        AdminUserTable user = dao.getOneByJobNumber(jobNumber);
        AssertUtil.assertNotNull(user, ErrorCodeDefine.USER_NOT_FOUND, ErrorCodeDefine.USER_NOT_FOUND_MSG);
        AssertUtil.assertTrue(user.getPassword().equals(password), ErrorCodeDefine.USER_PASS_ERROR, ErrorCodeDefine.USER_PASS_ERROR_MSG);
        AssertUtil.assertTrue(StringUtils.equals(InvoiceReviewStatusEnum.PASS.getCode(), user.getReviewStatus()), ErrorCodeDefine.USER_NOT_REVIEW_ERROR, ErrorCodeDefine.USER_NOT_REVIEW_MSG);
        user.setLastLoginTime(new Date());
        dao.save(user);
        return ModelUtils.copySignModel(user, AdminUserModel.class);
    }

    public void register(AdminUserModel adminUserModel) {
        dao.save(ModelUtils.copySignModel(adminUserModel, AdminUserTable.class));
    }

    public AdminUserModel getUserInfo(Long id) {
        AdminUserTable user = dao.findOne(id);
        AssertUtil.assertNotNull(user, ErrorCodeDefine.USER_NOT_FOUND, ErrorCodeDefine.USER_NOT_FOUND_MSG);
        AdminUserModel model = ModelUtils.copySignModel(user, AdminUserModel.class);
        model.setLastLoginTime(DateFormatUtil.format(user.getLastLoginTime(), DateFormatUtil.DATE_RULE_1));
        return model;
    }

    public void updateUserInfo(AdminUserModel model) {
        userAdminService.add(model);
    }

    public void changePassword(Long id, String oldPassword, String newPassword){
        AdminUserTable user = dao.findOne(id);
        AssertUtil.assertNotNull(user, ErrorCodeDefine.USER_NOT_FOUND, ErrorCodeDefine.USER_NOT_FOUND_MSG);
        AssertUtil.assertTrue(user.getPassword().equals(oldPassword), ErrorCodeDefine.USER_PASS_ERROR, ErrorCodeDefine.USER_PASS_ERROR_MSG);
        user.setPassword(newPassword);
        user.setPasswordStatus(Constants.USER_CUSTOMER);
        dao.save(user);
    }
}
